package cn.springcloud.fix.security.query;

import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.data.spel.spi.EvaluationContextExtension;

public class SecurityEvaluationContextExtension implements EvaluationContextExtension {

    private Authentication authentication;

    public SecurityEvaluationContextExtension() {
    }

    public SecurityEvaluationContextExtension(Authentication authentication) {
        this.authentication = authentication;
    }

    @Override
    public String getExtensionId() {
        return "security";
    }

    @Override
    public Object getRootObject() {
        Authentication authentication = getAuthentication();
        return new SecurityExpressionRoot(authentication) {
        };
    }

    private Authentication getAuthentication() {
        if (this.authentication != null) {
            return this.authentication;
        }

        SecurityContext context = SecurityContextHolder.getContext();
        return context.getAuthentication();
    }
}
